package com.ido.switchmodel.hot

import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.ido.switchmodel.bean.SMBeanResponse
import com.ido.switchmodel.util.SMSignUtil
import com.ido.switchmodel.util.SwitchModelConfig
import com.ido.switchmodel.util.SwitchModelPreferenceSetting
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.interceptor.HttpLoggingInterceptor
import com.lzy.okgo.model.Response
import okhttp3.OkHttpClient
import java.io.UnsupportedEncodingException
import java.util.concurrent.TimeUnit
import java.util.logging.Level

/**
 * 热启动 也就是从后台进入后的闪屏
 */
class HotSplash : SMHotInterface {
    private val gson = Gson()

    override fun init(
        context: Context,
        packageName: String,
        version: String,
        channel: String,
        type: String
    ) {
        try {
            //每个请求都有一个.client()方法可以传递一个OkHttpClient对象，表示当前这个请求将使用外界传入的这个OkHttpClient对象，其他的请求还是使用全局的保持不变。配置什么东西，改个超时时间，加个拦截器什么的统统都是可以
            val builder = OkHttpClient.Builder()
            builder.readTimeout(30, TimeUnit.SECONDS)
            builder.connectTimeout(30, TimeUnit.SECONDS)
            builder.writeTimeout(30, TimeUnit.SECONDS)
            //以下为打印log拦截器
            if (SwitchModelConfig.DEBUG) {
                Log.e(SwitchModelConfig.Tag, "channel:$channel version:$version packageName:$packageName")
                val loggingInterceptor = HttpLoggingInterceptor(SwitchModelConfig.Tag)
                loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY)
                loggingInterceptor.setColorLevel(Level.INFO)
                builder.addInterceptor(loggingInterceptor)
            }
            val time = (System.currentTimeMillis() / 1000)
            val sign = SMSignUtil.makeSign(SwitchModelConfig.appid, SwitchModelConfig.appKey, time)
            OkGo.post<String>(SwitchModelConfig.SERVER + System.currentTimeMillis())
                .tag(SwitchModelConfig.Tag)
                .cacheMode(CacheMode.NO_CACHE)
                .retryCount(0)
                .isMultipart(true)
                .params("appId", SwitchModelConfig.appid)
                .params("appSign", sign)
                .params("appTime", time.toString())
                .params("channel", channel)
                .params("packageName", packageName)
                .params("version", version)
                .params("type", type)
                .client(builder.build())
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        analysis(context, response?.body())
                    }

                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        Log.e(
                            SwitchModelConfig.Tag,
                            "HotSplash FialdException: " + response?.exception.toString()
                        )
                    }
                })

        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
            Log.e(
                SwitchModelConfig.Tag,
                "HotSplash UnsupportedEncodingException: " + e.message.toString()
            )
        }
    }

    private fun analysis(context: Context, json: String?) {
        if (json == null) {
            Log.e(SwitchModelConfig.Tag, "HotSplash FialdException: response.body() is Null")
        } else {
            try {
                val mResponse = gson.fromJson(json, SMBeanResponse::class.java)
                if (mResponse != null) {
                    if (!mResponse.data.isNullOrEmpty()) {
                        val isOpen = mResponse.data[0].isAdIsOpen
                        if (isOpen) {
                            setHot(context, mResponse)
                        } else {
                            Log.e(SwitchModelConfig.Tag, "HotSplash Off")
                            setOff(context)
                        }
                    } else {
                        Log.e(SwitchModelConfig.Tag, "HotSplash Off")
                        setOff(context)
                    }
                } else {
                    Log.e(
                        SwitchModelConfig.Tag,
                        "HotSplash FialdException: response fromJson is Null"
                    )
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Log.e(SwitchModelConfig.Tag, "HotSplash FromJsonException: " + e.message.toString())
            }
        }
    }

    private fun setOff(context: Context) {
        SwitchModelPreferenceSetting.setHotMode(context, 0)
        SwitchModelPreferenceSetting.setHotIntervalTime(context, -1)
    }


    private fun setHot(context: Context, bean: SMBeanResponse) {
        try {
            val time = if (bean.data[0].customDataMap.containsKey("time")) {
                (bean.data[0].customDataMap["time"] as Double).toInt()
            } else {
                -1
            }
            SwitchModelPreferenceSetting.setHotIntervalTime(context, time)
            val mode = if (bean.data[0].extendDataMap.containsKey("hotMode")) {
                (bean.data[0].extendDataMap["hotMode"] as Double).toInt()
            } else {
                0
            }
            SwitchModelPreferenceSetting.setHotMode(context, mode)
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(SwitchModelConfig.Tag, "HotSplash SetHotException: " + e.message.toString())
        }
    }


    override fun getHotMode(context: Context): Int {
        return SwitchModelPreferenceSetting.getHotMode(context)
    }

    override fun getHotIntervalTime(context: Context): Int {
        return SwitchModelPreferenceSetting.getHotIntervalTime(context)
    }

}